<template>
  <div class="login">
    <el-form
      ref="loginForms"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input
          style="width: 230px"
          v-model="ruleForm.username"
          autocomplete="off"
          clearable
          @keyup.enter.native="login"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          style="width: 230px"
          v-model="ruleForm.password"
          type="password"
          clearable
          show-password
          @keyup.enter.native="login"
        />
      </el-form-item>

      <el-form-item style="margin-left: 50px">
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { ElNotification } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import type { loginInDto } from 'dto/login/loginDto.ts'
import { getTime } from '@/utils/tools'

//user仓库
let userStore = useUserStore()
//路由
let $router = useRouter()
let $route = useRoute()
//是否加载
let loading = ref(false)

//获取el-form组件
let loginForms = ref()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (ruleForm.username !== '') {
      if (!loginForms.value) return
      loginForms.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validateUserName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}

const ruleForm: loginInDto = reactive({
  username: 'C111',
  password: '123456',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validateUserName, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

/**
 * 登录
 */
const login = async () => {
  //校验表单规则后不满足规则便中断函数，满足则继续执行
  await loginForms.value.validate()
  loading.value = true
  try {
    let loginData = JSON.parse(JSON.stringify(ruleForm))
    await userStore.userLogin(loginData)
    //获取其他页面传回的路由参数进行重定向
    let redirect: any = $route.query.redirect
    // console.log('114', redirect)
    $router.push({ path: redirect || '/' })

    ElNotification({
      type: 'success',
      message: '登录成功',
      title: 'Hi ' + getTime() + '好',
      duration: 2500,
    })
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
</script>

<style scoped lang="scss">
.login {
  width: 100%;
  height: 100vh;
  background: #021334;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
